package com.singzi.leetcode.jianzhiOffer2;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class T0037 {
    public static void main(String[] args) {
        Solution0037 solution0037 = new Solution0037();
        solution0037.asteroidCollision(new int[]{-2, 2, -1, -2});
    }
}
class Solution0037 {

    boolean flag = true;
    public int[] asteroidCollision(int[] asteroids) {

        List<Integer>list = new ArrayList<>();
        for(int i = 0;i < asteroids.length;i++){
            if(i != asteroids.length-1 && asteroids[i] > 0 && asteroids[i+1] < 0){
                flag = false;
                if(asteroids[i] + asteroids[i+1] == 0){
                    i = i+1;
                    continue;

                }
                else{
                    list.add(asteroids[i]  > -asteroids[i+1]?asteroids[i]:asteroids[i+1]);
                }
                i = i+1;
            }
            else{
                list.add(asteroids[i]);
            }
        }

        list = helper(list);

        int []objects = new int[list.size()];
        for(int i = 0;i < list.size();i++) {
            objects[i] = list.get(i);
        }

        return objects;

    }
    public List<Integer> helper(List<Integer>list){
        if(flag) return list;
        flag = true;
        List<Integer> ans = new ArrayList<>();
        for(int i = 0;i < list.size();i++){
            if(i != list.size()-1 && list.get(i) > 0 && list.get(i+1) < 0 ){
                flag = false;
                if(list.get(i) + list.get(i+1) == 0) continue;
                else{
                    ans.add(list.get(i)  > -list.get(i+1)?list.get(i):list.get(i+1));
                }
                i = i+1;
            }
            else{
                ans.add(list.get(i));
            }
        }
        return helper(ans);


    }

}